const nextIndex = (slide, offset) => {
    // 得到图片总数和当前图片下标
    let numberOfImgs = parseInt(slide.dataset.imgs, 10)
    // 因为得到的是 string 类型, 所以用 parseInt 转成 number
    // 也可以用 Number() 来转
    let activeIndex = Number(slide.dataset.active)
    let i = (activeIndex + offset + numberOfImgs) % numberOfImgs
    return i
}

const bindEventSlide = () => {
    let selector = '.panda-slide-button'
    bindAll(selector, 'click', function(event) {
        let button = event.target
        // 找到 slide div
        let slide = button.parentElement
        let offset = Number(button.dataset.offset)
        // 求出下一张图片的 index
        let index = nextIndex(slide, offset)
        // 显示下一张图片
        showImageAtIndex(slide, index)
    })
}

const showImageAtIndex = (slide, index) => {
    let nextIndex = index
    // 设置父节点的 data-active
    slide.dataset.active = String(nextIndex)
    // 删除当前图片的 class 给下一张图片加上 class
    let className = 'panda-active'
    removeClassAll(className)

    let nextSelector = '#id-pandaimage-' + String(nextIndex)
    let img = e(nextSelector)
    img.classList.add(className)

    // 切换小圆点
    // 1. 删除当前小圆点的 class
    removeClassAll('panda-white')
    // 2. 得到下一个小圆点的选择器
    let dotSelector = '#id-dot-' + String(nextIndex)
    let dot = e(dotSelector)
    dot.classList.add('panda-white')
}

const bindEventDot = () => {
    autoTimer()
    let selector = '.panda-slide-dot'
    bindAll(selector, 'mouseover', function(event) {
        let self = event.target
        let index = Number(self.dataset.index)
        // 直接播放第 n 张图片
        let slide = self.closest('.panda-slide')
        showImageAtIndex(slide, index)
    })
}

const bindEvents = () => {
    bindEventSlide()
    bindEventDot()
}

const playNextImage = () => {
    autoTimer()
    let slide = e('.panda-slide')
    let index = nextIndex(slide, 1)
    showImageAtIndex(slide, index)
}

let autoplay

const autoTimer = (bo = true) => {
    if (autoplay) {
        clearTimeout(autoplay)
    }
    if (bo) {
        autoplay = setInterval(() => {
            playNextImage()
        }, 2000)
    }
}

const __main = () => {
    bindEvents()
    autoTimer()
}

__main()
